package com.uestc.shop.service.impl;

import com.uestc.shop.dao.ProductRepository;
import com.uestc.shop.domain.Product;
import com.uestc.shop.service.IProductService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * @Package: com.uestc.shop.service
 * @author: hujiansong
 * @date: 2018/7/26 17:56
 * @version: V1.0
 */
@Service
public class ProductServiceImpl implements IProductService {

    @Autowired
    ProductRepository repository;

    @Override
    public Product save(Product product) {

        Product entity = repository.saveAndFlush(product);
        if (entity.getId() > 0) {
            return entity;
        }

        return null;
    }

    @Override
    public Page<Product> search(int page, int size, String keywords) {
        if (StringUtils.isEmpty(keywords)) {
            //keywords 为空，那么就%%
            keywords = "%%";
        }else{
            keywords = "%"+keywords+"%";
        }

        if (size == 0) {
            // 默认返回十条
            size = 10;
        }

        Page<Product> product = repository.findByNameLikeOrDetailLike(keywords, keywords, new PageRequest(page, size));
        return product;
    }
}
